package net.guerlab.sdk.dingtalk.storage;

import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * 钉钉配置储存接口-spring redis template实现
 *
 * @author guer
 */
public class DingTalkConfigRedisTemplateStorage extends DingTalkConfigMemoryStorage {

    private static final String ACCESS_TOKEN_KEY = "dingTalk:access_token:%s:%s";

    private final RedisTemplate<String, String> redisTemplate;

    public DingTalkConfigRedisTemplateStorage(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    private String getRedisKey() {
        return String.format(ACCESS_TOKEN_KEY, getCorpId(), getAppKey());
    }

    @Override
    public String getAccessToken() {
        return redisTemplate.opsForValue().get(getRedisKey());
    }

    @Override
    public boolean isAccessTokenExpired() {
        Long expire = redisTemplate.getExpire(getRedisKey(), TimeUnit.SECONDS);
        return expire == null || expire < 2;
    }

    @Override
    public synchronized void updateAccessToken(String accessToken, long expiresInSeconds) {
        redisTemplate.opsForValue().set(getRedisKey(), accessToken, expiresInSeconds - 200, TimeUnit.SECONDS);
    }

    @Override
    public void expireAccessToken() {
        redisTemplate.expire(getRedisKey(), 0, TimeUnit.SECONDS);
    }
}
